import { createStore } from 'vuex';

function includes (s, t) {
  if (!s || !t) {
    return false;
  }

  let rs = false;
  let keys = Reflect.ownKeys(s);

  for (let item of keys) {
    if (s[item] == t[item]) {
      rs = true;

      break;
    }
  }

  return rs;
}

export default createStore({
  state: {
    navs: [],
    oauth: {
      enable: false,
      access_token: '',
      expires_in: 0,
      refresh_token: '',
      at: 0
    },
    user: {
      userId: '',
      userAccount: '',
      userName: '',
      authenticated: false
    },
    area: {
      content: {
        height: 300,
        width: 1024
      },
      tableDetail: {
        height: 500
      }
    },
    requestTypes: ['query', 'body', 'header']
  },
  mutations: {
    navs (state, navs) {
      state.navs = navs;
    },
    authcate (state, token) {
      state.oauth.enable = true;
      state.oauth.access_token = token.access_token;
      state.oauth.expires_in = token.expires_in;
      state.oauth.refresh_token = token.refresh_token;

      state.oauth.at = new Date().getTime() / 1000;
    },
    logOff (state) {
      state.user.userId = null;
      state.user.userAccount = null;
      state.user.userName = null;

      state.user.authenticated = false;

      sessionStorage.clear();
    },
    fillConfigs (state, config) {
      state.user.userId = config.userId;
      state.user.userAccount = config.userAccount;
      state.user.userName = config.userName;

      state.user.authenticated = !!config.userId;

      sessionStorage.setItem('auth', JSON.stringify(state.user));
      sessionStorage.setItem('authedTime', new Date().getTime());
    },
    contentArea (state, area) {
      state.area.content.height = area.height;
      state.area.content.width = area.width || 1024;
    },
    resetNav (state, supported) {
      if (!supported) {
        return state.navs;
      }

      let clonedNavs = JSON.parse(JSON.stringify(state.navs));
      let tmpNavs = clonedNavs.filter(f => f.limit == undefined || includes(supported, f.limit));

      tmpNavs.forEach(n => {
        if (n.subMenus) {
          n.subMenus = n.subMenus.filter(f => f.limit == undefined || includes(supported, f.limit));
        }
      });

      state.navs = tmpNavs;

      return state.navs;
    }
  },
  getters: {
    tokenIsExpires (state) {
      return () => {
        let nowAt = new Date().getTime() / 1000;

        return nowAt + 30 > state.oauth.at + state.oauth.expires_in;
      }
    },
    getOperators (state) {
      return (currentRoute) => {
        let crumbs = [{ title: '工作台', path: '/' }];
        let path = window.location.hash.replace(/#/g, '');
        let matchedPath = new RegExp('_____');

        if (path.indexOf('?') != -1) {
          path = path.substring(0, path.indexOf('?'));
        }

        path = path.toLowerCase();

        if (currentRoute && currentRoute.matched && path != '/') {
          let matched = '^' + currentRoute.matched[currentRoute.matched.length - 1].path;
          let keys = Object.keys(currentRoute.params);

          for (let k of keys) {
            matched = matched.replace(`:${k}`, '.+', 'ig');
          }

          matchedPath = new RegExp(matched);
        }

        for (let nav of state.navs) {
          if (nav.path == '/') {
            continue;
          }

          if ((nav.path || '').toLowerCase() == path || matchedPath.test(nav.name)) {
            crumbs.push(nav);

            break;
          }

          if (!nav.subMenus) {
            continue;
          }

          for (let sub of nav.subMenus) {
            if ((sub.path || '').toLowerCase() == path || matchedPath.test(sub.name)) {
              crumbs.push(nav);
              crumbs.push(sub);

              break;
            }

            if (!sub.subMenus) {
              continue;
            }

            for (let sub2 of sub.subMenus) {
              if ((sub2.path || '').toLowerCase() == path || matchedPath.test(sub2.name)) {
                crumbs.push(nav);
                crumbs.push(sub);
                crumbs.push(sub2);

                break;
              }
            }
          }
        }

        return (crumbs[crumbs.length - 1] || { operators: [] }).operators;
      };
    },
    getCrumbs (state) {
      return (currentRoute) => {
        let crumbs = [{ title: '工作台', path: '/' }];
        let path = window.location.hash.replace(/#/g, '');
        let matchedPath = new RegExp('_____');

        if (path.indexOf('?') != -1) {
          path = path.substring(0, path.indexOf('?'));
        }

        path = path.toLowerCase();

        if (currentRoute && currentRoute.matched && path != '/') {
          let matched = '^' + currentRoute.matched[currentRoute.matched.length - 1].path;

          if (currentRoute.params) {
            let keys = Object.keys(currentRoute.params);

            for (let k of keys) {
              matched = matched.replace(`:${k}`, '.+', 'ig');
            }
          }

          matchedPath = new RegExp(matched);
        }

        for (let nav of state.navs) {
          if (nav.path == '/') {
            continue;
          }

          if ((nav.path || '').toLowerCase() == path || matchedPath.test(nav.path)) {
            crumbs.push(nav);

            break;
          }

          if (!nav.subMenus) {
            continue;
          }

          for (let sub of nav.subMenus) {
            if ((sub.path || '').toLowerCase() == path || matchedPath.test(sub.path)) {
              crumbs.push({ title: nav.title, path: nav.path, icon: nav.icon });
              crumbs.push(sub);

              break;
            }

            if (!sub.subMenus) {
              continue;
            }

            for (let sub2 of sub.subMenus) {
              if ((sub2.path || '').toLowerCase() == path || matchedPath.test(sub2.path)) {
                crumbs.push({ title: nav.title, path: nav.path, icon: nav.icon });
                crumbs.push({ title: sub.title, path: sub.path, icon: sub.icon });
                crumbs.push(sub2);

                break;
              }
            }
          }
        }

        if (crumbs.length == 1 && path != '/') {
          let sessionCrumbs = sessionStorage.getItem('crumbs');

          crumbs = sessionCrumbs ? JSON.parse(sessionCrumbs) : crumbs;
        }

        sessionStorage.setItem('crumbs', JSON.stringify(crumbs));

        return crumbs;
      };
    }
  },
  actions: {
  },
  modules: {
  }
})
